<template>
	<view>
		<view class="form-view">
			<view class="form-card">
				<view class="form-row">
					<view class="label">标题</view>
					<view class="placeholder-class">请选择</view>
					<uni-icons 
						type="right"
						color="rgba(35,35,35,0.4)"/>
				</view>
				<view class="div-line-type-1"/>
				<view class="form-row">
					<view class="label">标题</view>
					<view class="placeholder-class">请选择</view>
					<uni-icons 
						type="right" 
						color="rgba(35,35,35,0.4)"/>
				</view>
			</view>
			
			<view class="form-desc-form">
				<textarea 
				placeholder-class="placeholder-class"
				placeholder="请填写您对本次服务的总结，以便其他医护人员全面了解该患者的情况">
				</textarea>
				<view class="div-line"/>
				<view class="label">附图（选填）</view>
				<uni-grid :column="3" :highlight="false" :showBorder="false">
					<uni-grid-item v-for="item in list">
						<view class="image-grid-item" @click="previewImage(item)">
							<image :src="item"></image>
						</view>
					</uni-grid-item>
					<uni-grid-item>
						<view class="image-grid-item" @click="uploadImg">
							<view class="grid-item-add">
								<uni-icons type="plusempty" color="#232323"/>
								<view>上传图片</view>
							</view>
						</view>
					</uni-grid-item>
				</uni-grid>
			</view>
			
			<view class="switch-tab-view">
				<view class="label">下次预约服务时间</view>
				<view class="tab-view">
					<view 
						@click="tabClick(item,index)"
						:class="current === index ? 'tab-item-selected' : ''"
						v-for="item,index in tabs" 
						class="tab-item">{{item}}</view>
				</view>
			</view>
			
			<view class="form-card last-view">
				<view class="form-row">
					<view class="label">废弃物名称</view>
					<input placeholder="请输入" placeholder-class="placeholder-class"/>
				</view>
				<view class="div-line-type-1"/>
				<view class="form-row">
					<view class="label">投放地点</view>
					<input placeholder="请输入" placeholder-class="placeholder-class"/>
				</view>
				
				<view class="form-desc-form">
					<view class="label">医疗废弃物品投放照片（选填）</view>
					<uni-grid :column="3" :highlight="false" :showBorder="false">
						<uni-grid-item v-for="i in 0">
							<view class="image-grid-item">
								<image src="../../static/logo.png"></image>
							</view>
						</uni-grid-item>
						<uni-grid-item>
							<view class="image-grid-item">
								<view class="grid-item-add">
									<uni-icons type="plusempty" color="#232323"/>
									<view>上传图片</view>
								</view>
							</view>
						</uni-grid-item>
					</uni-grid>
				</view>
				
			</view>
			
			<view class="bottom-fixed-view">
				<view class="submit-btn">确认完成</view>
			</view>
			
			<view class="watermark-canvas">
				<canvas
					v-if="showCanvas"
					id="watermark-canvas"
					:style="{ width: canvasWidth, height: canvasHeight }"
					canvas-id="watermark-canvas"
				/>
			</view>
			
		</view>
	</view>
</template>

<script>
	import * as upload from '../../common/upload.js'
	export default {
		data() {
			return {
				tabs:['一周内','半个月内','一个月内','暂不预约'],
				current:0,
				canvasWidth:'',
				canvasHeight:'',
				showCanvas:true,
				list:[]
			}
		},
		methods: {
			tabClick(item,index){
				this.current = index
			},
			previewImage(url){
				uni.previewImage({
					urls:[url]
				})
			},
			getAddress(longitude,latitude){
				return new Promise((resolve, reject) => {
					const key = '3cba451d85dfb3a05aebd8d3a70ed2c1'//高德地图key
					uni.request({
						url:`https://restapi.amap.com/v3/geocode/regeo?output=json&location=${longitude},${latitude}&key=${key}&radius=1000&extensions=all`,
						data: {},
						header: {
								'Content-Type': 'application/json',
								'Access-Control-Allow-Origin':'*'
						},
						success(res){
								console.log('高德地图API接口返回信息',res)
								console.log(res.data.regeocode.formatted_address);
								resolve(res.data.regeocode.formatted_address)
						},
						fail() {
							reject()
						}
					})
				})
			},
			getLocation(){
				return new Promise((resolve, reject) => {
					uni.getLocation({
						type: 'wgs84',
						geocode:true,
						success(res) {
							console.log(JSON.stringify(res));
							console.log('当前位置的经度：' + res.longitude);
							console.log('当前位置的纬度：' + res.latitude);
							resolve(res)			
						},
						fail() {
							reject()
						}
					})
				})
			},
			async addWatermark(tempFilePath) {
				function sleep(millisecond) {
					return new Promise((resolve) => {
						setTimeout(resolve, millisecond)
					})
				}
				return new Promise((resolve, reject) => {
					uni.getImageInfo({
						src: tempFilePath,
						success: async (res) => {
							//重新渲染canvas
							this.showCanvas = false
							this.$nextTick(()=>{
								this.showCanvas = true
							})
							// 设置画布高度和宽度
							this.canvasWidth = `${res.width}px`
							this.canvasHeight = `${res.height}px`
							await sleep(200) // 某些平台 canvas 渲染慢，需要等待
							
							const ctx = uni.createCanvasContext('watermark-canvas', this)
							ctx.clearRect(0, 0, res.width, res.height)
							ctx.beginPath()
							ctx.drawImage(tempFilePath, 0, 0, res.width, res.height)

							// 水印 字体大小，颜色，内容，位置
							ctx.beginPath()
							ctx.setFontSize(24)
							ctx.setFillStyle('rgba(250,0,0,0.8)')
							//拍照时间、星期几，经纬度，地区
							const date = new Date()
							const dateText = date.format("yyyy-MM-dd hh:mm:ss")
							const weekArr = ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"]
							const week = weekArr[date.getDay()]
							const location = await this.getLocation()
							const longitude = location.longitude || ''//经度
							const latitude = location.latitude || ''//经度
							const address = await this.getAddress(longitude,latitude)
							const left = 30
							const bottom = 30
							ctx.fillText(`拍照时间 ${dateText} ${week}`, left, res.height - (bottom * 4) )
							ctx.fillText(`经度 ${longitude}`, left, res.height - (bottom * 3) )
							ctx.fillText(`纬度 ${latitude}`, left, res.height - (bottom * 2) )
							ctx.fillText(`地区 ${address}`, left, res.height - (bottom * 1) )
							// 开始绘制 (canvas -> 临时文件路径)
							ctx.draw(false, async () => {
								await sleep(500) // 某些平台 canvas 渲染慢，需要等待
								uni.canvasToTempFilePath(
									{
										canvasId: 'watermark-canvas',
										destWidth: res.width,
										destHeight: res.height,
										fileType: 'jpg',
										quality: 0.8,
										success: (fileRes) => {
											resolve(fileRes.tempFilePath)
										},
										fail: (err) => {
											console.log('[Error draw]', err)
											uni.showToast({ title: err.errMsg, icon: 'none' })
											reject()
										},
									},
									this,
								)
							})
						},
						fail: (err) => {
							console.log('[Error getImageInfo]', err)
							uni.showToast({ title: err.errMsg, icon: 'none' })
							reject()
						},
					})
				})
			},
			uploadImg(){
				uni.chooseImage({
					success:async (res)=>{
						console.log(res.tempFilePaths);
						const img = await this.addWatermark(res.tempFilePaths[0])
						this.list.push(img)
					}
				})
			},
			
		}
	}
</script>

<style lang="scss" scoped>
.form-view{
	width: 100%;
	display: flex;
	flex-direction: column;
}

.form-card{
	background: white;
	.form-row{
		display: flex;
		background: white;
		padding: 0 30rpx;
		height: 120rpx;
		align-items: center;
		.label{
			flex: 1;
			color: #232323;
			font-size: 32rpx;
			font-weight: bold;
		}
		
		input{
			text-align: end;
		}
		.placeholder-class{
			color: rgba(35,35,35,0.4);
			font-size: 32rpx;
		}
		.uni-icons{
			margin-left: 16rpx;
		}
		
	}
	.div-line-type-1{
		width: calc(100% - 30rpx);
		background: #F8F8F8;
		height: 2rpx;
		margin-left: 30rpx;
	}
	
}

.form-desc-form{
	background: white;
	width: 100%;
	display: flex;
	flex-direction: column;
	padding: 30rpx;
	box-sizing: border-box;
	margin-top: 20rpx;
	textarea{
		width: 100%;
	}
	.placeholder-class{
		color: rgba(35,35,35,0.4);
		font-size: 32rpx;
	}
	.div-line{
		width: 100%;
		height: 2rpx;
		background: #F8F8F8;
	}
	.label{
		color: rgba(35,35,35,0.5);
		font-size: 26rpx;
		margin-top: 20rpx;
	}
}

.image-grid-item{
	width: 100%;
	height: 100%;
	padding: 10rpx;
	box-sizing: border-box;
	image{
		width: 100%;
		height: 100%;
		border-radius: 12rpx;
	}
	.grid-item-add{
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background: #FDFDFD;
		border-radius: 12rpx;
		border: dashed 2rpx #E1E1E1;
		color: rgba(35,35,35,0.7);
		font-size: 24rpx;
	}
	
}


.switch-tab-view{
	width: 100%;
	padding: 30rpx;
	background: white;
	box-sizing: border-box;
	margin-top: 20rpx;
	.label{
		color: #232323;
		font-size: 32rpx;
	}
	.tab-view{
		margin-top: 30rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		.tab-item{
			background: #F6F6F6;
			min-width: 160rpx;
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 40rpx;
			color: rgba(35,35,35,0.8);
			font-size: 26rpx;
		}
		.tab-item-selected{
			background: #2EB0D9;
			color: white;
		}
	}
}

.last-view{
	margin-top: 20rpx;
	margin-bottom: 130rpx;
}


.bottom-fixed-view{
	width: 100%;
	height: 108rpx;
	position: fixed;
	background: white;
	padding: 14rpx 30rpx;
	box-sizing: border-box;
	bottom: 0;
	.submit-btn{
		width: 100%;
		height: 80rpx;
		background: #2EB0D9;
		border-radius: 40rpx;
		color: white;
		font-size: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
}

.watermark-canvas {
	position: absolute;
	top: 5px;
	left: 5px;
	width: 1px;
	height: 1px;
	overflow: hidden;
}
</style>
